package com.abcd.sign;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @program: java-base
 * @description:
 * @author: Liu
 **/
public class SignUtils {

    /**
     * 把数组所有元素排序，并将排序的的参数值拼接成字符串
     *
     * @param params
     *          需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkStringWithoutParamName(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    public static String formatSync_yMdTHmsZ(Date srcDate) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(srcDate);
    }


    /**
     * 正则
     * @param str
     * @return
     */
    public static boolean pointRegex(String str){
        boolean flag = true;
        flag = Pattern.matches("^zc[0-9]{19}",str);
        return flag;
    }


    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
        // 16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，需要前面补0
        StringBuilder builder = new StringBuilder(md5code);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            builder = builder.append("0");
        }
        return String.valueOf(builder);
    }


}